import 'dart:convert';
import 'dart:ui';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:gzx_dropdown_menu/gzx_dropdown_menu.dart';
import 'package:panda/base/Constant.dart';
import 'package:panda/entity/good_list_entity.dart';
import 'package:panda/http/Api.dart';
import 'package:panda/http/HttpUtil.dart';

import '../base/Constant.dart';
import '../base/Constant.dart';
import 'GoodsDetail.dart';

class GoodsListPage extends StatefulWidget {
  String cat_id = "";
  GoodsListPage({Key key, @required this.cat_id}) : super(key: key);

  _GoodsListPageState createState() => _GoodsListPageState();
}

class _GoodsListPageState extends State<GoodsListPage> {
  List<GoodsListDataData> homeListData = new List();

  GZXDropdownMenuController _dropdownMenuController =
      GZXDropdownMenuController();
  List<String> sortList = ["距离", "销量"];
  var _scaffoldKey = new GlobalKey<ScaffoldState>();
  GlobalKey _stackKey = GlobalKey();
  EasyRefreshController _controller = new EasyRefreshController();
  int page = 1;
  int currentShow = 0; //0 正常 1 网格
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    loadList();
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);

    return Container(
      child: new Scaffold(
          appBar: PreferredSize(
            child: AppBar(
              brightness: Brightness.light,
              backgroundColor: white,
              elevation: 0,
            ),
            preferredSize: Size(0, 0),
          ),
          body: new Stack(
            key: _stackKey,
            children: <Widget>[
              new Column(
                children: <Widget>[
                  Container(
                    height: kToolbarHeight,
                    color: white,
                    alignment: Alignment.center,
                    child: new Row(
                      children: <Widget>[
                        Padding(
                          padding: EdgeInsets.all(0),
                          child: IconButton(
                            onPressed: () {
                              Navigator.of(context).pop();
                            },
                            icon: Icon(
                              Icons.arrow_back_ios,
                              color: black_99,
                            ),
                          ),
                        ),
                        Expanded(
                          flex: 1,
                          child: Container(
                            margin: EdgeInsets.fromLTRB(
                                ScreenUtil.getInstance().setHeight(DP_10),
                                0,
                                ScreenUtil.getInstance().setHeight(DP_10),
                                0),
                            height: ScreenUtil.getInstance().setHeight(DP_60),
                            decoration: BoxDecoration(
                                color: Color.fromARGB(255, 245, 245, 245),
                                borderRadius: BorderRadius.circular(20.0)),
                            child: ConstrainedBox(
                              constraints: BoxConstraints(maxHeight: DP_80),
                              child: TextField(
                                keyboardAppearance: Brightness.light,
                                maxLines: 1,
                                cursorColor: mainColor,
                                decoration: new InputDecoration(
                                    // contentPadding: EdgeInsets.all(0),
                                    prefixIcon: Icon(
                                      Icons.search,
                                      color: Colors.black45,
                                    ),
                                    hintText: "搜索商品、品牌",
                                    suffixIcon: ClipOval(
                                      child: Container(
                                        child: Icon(
                                          Icons.clear,
                                          color: Colors.white,
                                          size: ScreenUtil.getInstance()
                                              .setHeight(DP_30),
                                        ),
                                        margin: EdgeInsets.fromLTRB(
                                            80,
                                            ScreenUtil.getInstance()
                                                .setHeight(DP_15),
                                            ScreenUtil.getInstance()
                                                .setHeight(DP_15),
                                            ScreenUtil.getInstance()
                                                .setHeight(DP_15)),
                                        decoration: BoxDecoration(
                                            color: Colors.black45,
                                            borderRadius: BorderRadius.circular(
                                                ScreenUtil.getInstance()
                                                    .setHeight(DP_90))),
                                      ),
                                    ),
                                    border: InputBorder.none,
                                    hintStyle: TextStyle(
                                        color: Colors.black45,
                                        fontSize: ScreenUtil.getInstance()
                                            .setSp(NORMAL_FONT_SIZE))),
                              ),
                            ),
                          ),
                        ),
                        GestureDetector(
                          child: Container(
                              alignment: Alignment.center,
                              width: ScreenUtil.getInstance().setWidth(DP_120),
                              child: Text('确定',
                                  style: TextStyle(
                                      color: black_99,
                                      fontSize: ScreenUtil.getInstance()
                                          .setSp(NORMAL_FONT_SIZE)))),
                          onTap: () {
                            Navigator.of(context)
                                .push(new MaterialPageRoute(builder: (context) {
                              return new GoodsListPage(
                                cat_id: "5",
                              );
                            }));
                          },
                        )
                      ],
                    ),
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Expanded(
                        flex: 1,
                        child: GestureDetector(
                          child: Container(
                              alignment: Alignment.center,
                              height: ScreenUtil.getInstance().setHeight(DP_60),
                              color: white,
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: <Widget>[
                                  Text('全部',
                                      style: TextStyle(
                                          color: black_99,
                                          fontSize: ScreenUtil.getInstance()
                                              .setSp(SMALL_FONT_SIZE))),
                                  Icon(
                                    Icons.arrow_drop_down,
                                    size: ScreenUtil.getInstance()
                                        .setHeight(DP_40),
                                    color: black_99,
                                  )
                                ],
                              )),
                          onTap: () {
                            setState(() {
                              sortList = ["距离", "销量"];
                              if (_dropdownMenuController.isShow)
                                _dropdownMenuController.hide();
                            });
                          },
                        ),
                      ),
                      Expanded(
                        flex: 2,
                        child: Container(
                          color: white,
                          padding: EdgeInsets.fromLTRB(0,
                              ScreenUtil.getInstance().setHeight(DP_8), 0, 0),
                          height: ScreenUtil.getInstance().setHeight(DP_60),
                          child: GZXDropDownHeader(
                            items: [
                              GZXDropDownHeaderItem(sortList[0]),
                              GZXDropDownHeaderItem(sortList[1]),
                            ],
                            stackKey: _stackKey,
                            controller: _dropdownMenuController,
                            onItemTap: (index) {},
                            height: ScreenUtil.getInstance().setHeight(DP_60),
                            color: white,
                            borderWidth: 1,
                            borderColor: white,
                            dividerColor: white,
                            style: TextStyle(
                                color: black_99,
                                fontSize: ScreenUtil.getInstance()
                                    .setSp(SMALL_FONT_SIZE)),
                            dropDownStyle: TextStyle(
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(SMALL_FONT_SIZE),
                              color: mainColor,
                            ),
                            iconSize: ScreenUtil.getInstance().setHeight(DP_40),
                            iconColor: black_99,
                            iconDropDownColor: mainColor,
                          ),
                        ),
                      ),
                      Container(
                        height: ScreenUtil.getInstance().setHeight(DP_60),
                        color: white,
                        child: IconButton(
                          onPressed: () {
                            setState(() {
                              currentShow =
                                  (currentShow == 0 ? currentShow = 1 : 0);
                            });
                          },
                          icon: Image.asset(currentShow == 1
                              ? 'images/icon_list_vertical.png'
                              : 'images/icon_list_transverse.png'),
                        ),
                      ),
                    ],
                  ),
                  new Container(
                    height: MediaQuery.of(context).size.height -
                        kToolbarHeight -
                        ScreenUtil.getInstance().setHeight(DP_60) -
                        MediaQueryData.fromWindow(window).padding.top,
                    color: f0Color,
                    child: new EasyRefresh(
                      controller: _controller,
                      header: MaterialHeader(),
                      footer: MaterialFooter(),
                      enableControlFinishLoad: true,
                      enableControlFinishRefresh: true,
                      child: currentShow == 0
                          ? ListView.separated(
                              itemBuilder: _renderRow,
                              separatorBuilder:
                                  (BuildContext context, int index) {
                                return Container(
                                  color: divideColor,
                                  height: 1,
                                );
                              },
                              itemCount: homeListData == null
                                  ? 0
                                  : homeListData.length)
                          : GridView.builder(
                              shrinkWrap: true,
                              gridDelegate:
                                  SliverGridDelegateWithFixedCrossAxisCount(
                                      crossAxisCount: 2,
                                      mainAxisSpacing: 10.0,
                                      crossAxisSpacing: 10.0,
                                      childAspectRatio: 0.7),
                              itemBuilder: (context, index) {
                                return _renderRow2(context, index);
                              },
                              itemCount: homeListData == null
                                  ? 0
                                  : homeListData.length,
                            ),
                      onRefresh: () async {
                        page = 1;
                        loadList();
                      },
                      onLoad: () async {
                        page++;
                        loadList();
                      },
                    ),
                  ),
                ],
              ),
              GZXDropDownMenu(
                controller: _dropdownMenuController,
                animationMilliseconds: 0,
                menus: [
                  GZXDropdownMenuBuilder(
                      dropDownHeight:
                          ScreenUtil.getInstance().setHeight(DP_60) * 2 + 2,
                      dropDownWidget: new Column(
                        children: <Widget>[
                          Divider(
                            height: 1,
                            color: grey,
                          ),
                          new GestureDetector(
                            onTap: () {
                              setState(() {
                                sortList = ["距离", "销量"];
                                sortList[0] = "距离升序";
                                _dropdownMenuController.hide();
                              });
                            },
                            child: Container(
                              width: double.infinity,
                              height: ScreenUtil.getInstance().setHeight(DP_60),
                              padding: EdgeInsets.all(10),
                              child: Text('距离升序'),
                            ),
                          ),
                          Divider(
                            height: 1,
                            color: grey,
                          ),
                          new GestureDetector(
                            onTap: () {
                              setState(() {
                                sortList = ["距离", "销量"];
                                sortList[0] = "距离降序";
                                _dropdownMenuController.hide();
                              });
                            },
                            child: Container(
                              width: double.infinity,
                              height: ScreenUtil.getInstance().setHeight(DP_60),
                              padding: EdgeInsets.all(10),
                              child: Text('距离降序'),
                            ),
                          ),
                        ],
                      )),
                  GZXDropdownMenuBuilder(
                      dropDownHeight:
                          ScreenUtil.getInstance().setHeight(DP_60) * 2 + 2,
                      dropDownWidget: new Column(
                        children: <Widget>[
                          Divider(
                            height: 1,
                            color: grey,
                          ),
                          new GestureDetector(
                            onTap: () {
                              setState(() {
                                sortList = ["距离", "销量"];
                                sortList[1] = "销量升序";
                                _dropdownMenuController.hide();
                              });
                            },
                            child: Container(
                              width: double.infinity,
                              height: ScreenUtil.getInstance().setHeight(DP_60),
                              padding: EdgeInsets.all(10),
                              child: Text('销量升序'),
                            ),
                          ),
                          Divider(
                            height: 1,
                            color: grey,
                          ),
                          new GestureDetector(
                            onTap: () {
                              setState(() {
                                sortList = ["距离", "销量"];
                                sortList[1] = "销量降序";
                                _dropdownMenuController.hide();
                              });
                            },
                            child: Container(
                              width: double.infinity,
                              height: ScreenUtil.getInstance().setHeight(DP_60),
                              padding: EdgeInsets.all(10),
                              child: Text('销量降序'),
                            ),
                          ),
                        ],
                      )),
                ],
              ),
            ],
          )),
    );
  }

  loadList() async {
    FormData formData = new FormData.fromMap({
      "cat_id": widget.cat_id,
      "p": page,
      "per": 8,
    });
    Response<String> response =
        await HttpUtil().post(Api.GET_GOODS_LIST, data: formData);
    Map userMap = json.decode(response.data);
    GoodsListEntity homeListEntity = new GoodsListEntity.fromJson(userMap);
    setState(() {
      if (page == 1) {
        homeListData.clear();
        homeListData.addAll(homeListEntity.data.datas);
        _controller.finishRefresh();
      } else {
        homeListData.addAll(homeListEntity.data.datas);
        _controller.finishLoad();
      }
    });
  }

  Widget _renderRow(BuildContext context, int index) {
    return new GestureDetector(
      onTap: () {
        Navigator.of(context).push(MaterialPageRoute(builder: (context) {
          return GoodsDetailPage(
            goods_id: homeListData[index].goods_id,
            img: homeListData[index].img,
          );
        }));
      },
      child: Container(
        padding: EdgeInsets.all(10),
        color: white,
        child: new Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            homeListData[index].img == ""
                ? Image.asset('images/app_icon.png',
                    width: ScreenUtil.getInstance().setWidth(180),
                    fit: BoxFit.fill,
                    height: ScreenUtil.getInstance().setWidth(180))
                : CachedNetworkImage(
                imageUrl:
                    Api.BaseUrl + homeListData[index].img,
                    width: ScreenUtil.getInstance().setHeight(180),
                    height: ScreenUtil.getInstance().setHeight(180),
                    fit: BoxFit.fill,
                  ),
            Expanded(
              flex: 1,
              child: Container(
                padding: EdgeInsets.fromLTRB(10, 5, 5, 5),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      homeListData[index].goods_name,
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                          fontSize: ScreenUtil.getInstance().setSp(32),
                          color: black,
                          fontWeight: FontWeight.w400),
                    ),
                    Padding(
                      padding: EdgeInsets.fromLTRB(0, 3, 5, 0),
                      child: Text(
                        homeListData[index].description,
                        style: TextStyle(
                          fontSize: ScreenUtil.getInstance().setSp(26),
                          color: black_99,
                        ),
                      ),
                    ),
                    new Row(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: <Widget>[
                        Expanded(
                          child: Text(
                            "¥" + homeListData[index].price.toString(),
                            style: TextStyle(
                                fontSize: ScreenUtil.getInstance().setSp(36),
                                color: mainColor),
                          ),
                        ),
                        // Padding(
                        //   padding: EdgeInsets.fromLTRB(0, 0, 5, 0),
                        //   child: Image.asset(
                        //     'images/icon_shop_car.png',
                        //     height: ScreenUtil.getInstance().setHeight(50),
                        //   ),
                        // )
                      ],
                    )
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _renderRow2(BuildContext context, int index) {
    return GestureDetector(
      child: Container(
        padding: EdgeInsets.fromLTRB(
            10, ScreenUtil.getInstance().setHeight(20), 10, 0),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10.0),
          color: white,
        ),
        width: MediaQuery.of(context).size.width / 2,
        child: new Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            homeListData[index].img == ""
                ? Image.asset('images/app_icon.png',
                    width: ScreenUtil.getInstance().setWidth(260),
                    fit: BoxFit.fill,
                    height: ScreenUtil.getInstance().setWidth(260))
                : CachedNetworkImage(
                imageUrl:Api.BaseUrl + homeListData[index].img,
                    width: ScreenUtil.getInstance().setWidth(260),
                    fit: BoxFit.fill,
                    height: ScreenUtil.getInstance().setWidth(260)),
            Container(
              alignment: Alignment.centerLeft,
              child: Padding(
                padding: EdgeInsets.fromLTRB(0, 8, 0, 0),
                child: Text(
                  homeListData[index].goods_name,
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                      fontSize: 14,
                      color: black_99,
                      fontWeight: FontWeight.w500),
                ),
              ),
            ),
            Padding(
                padding: EdgeInsets.fromLTRB(0, 5, 0, 0),
                child: new Row(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: <Widget>[
                    Expanded(
                      child: Text(
                        "¥" + homeListData[index].price.toString(),
                        style: TextStyle(
                            fontSize: ScreenUtil.getInstance().setSp(34),
                            color: mainColor),
                      ),
                    ),
                    // Padding(
                    //   padding: EdgeInsets.fromLTRB(0, 0, 5, 0),
                    //   child: Image.asset(
                    //     'images/icon_shop_car.png',
                    //     height: ScreenUtil.getInstance().setHeight(50),
                    //   ),
                    // )
                  ],
                )),
          ],
        ),
      ),
      onTap: () {
        Navigator.of(context).push(MaterialPageRoute(builder: (context) {
          return GoodsDetailPage(
            goods_id: homeListData[index].goods_id,
            img: homeListData[index].img,
          );
        }));
      },
    );
  }
}
